
var getTreeItemType = function(node){
    var mnode = node;
    if (!node)
        mnode = Ext.getCmp('TreeID').getSelectionModel().getSelectedNode();    
    var type = 'none'
    if (mnode.attributes.hasOwnProperty('depid'))
        type = 'dep'
    else if(mnode.attributes.hasOwnProperty('prjid'))
        type = 'prj'
    else if(mnode.attributes.hasOwnProperty('devid'))
        type = 'dev'
    else if(mnode.attributes.hasOwnProperty('orgid'))
        type = 'org'
    return type
}

var getTreeItemID = function(id){
    var node;
    if (!id)
        node = Ext.getCmp('TreeID').getSelectionModel().getSelectedNode();
    else
        node = Ext.getCmp('TreeID').getNodeById(id);
    var type = getTreeItemType(node)
    if (type == 'org')
        return 'orgid='+node.attributes.orgid
    else if (type == 'dep')
        return 'depid='+node.attributes.depid
    else if (type == 'prj')
        return 'prjid='+node.attributes.prjid
    else if (type == 'dev')
        return 'devid='+node.attributes.devid
    return 'none=none'
}


var createAddForm = function()
{
	var type_item = getTreeItemID();
	var textarea = new Ext.form.TextField({
              xtype: 'textfield',
              id: 'name',
              fieldLabel: 'name',
              allowBlank:false,
              anchor: '100%'		
	});
	var addForm = new Ext.FormPanel({
	  url: 'application/create?'+type_item,
	  method: 'GET',
	  autoDestroy: true,
	  buttonAlign: 'center',
	  monitorValid:true,
	  items: [textarea],
	  buttons: [{
	        text: 'Add',
	        formBind:true,
	        handler: function() {
	            addForm.getForm().submit({
	                waitTitle: 'please wait...',
	                waitMsg: 'wait...',
   	                success: function(form, action) {
       					Ext.Msg.alert('Status', 'Action is successfully.');
       					Ext.getCmp('TreeID').getRootNode().reload();
       					Ext.getCmp('CreateFormID').close();
   	                },
                    failure: function(form,action){
                        console.info(action.result.errormsg)
                        Ext.Msg.alert('Status', 'Action is failed:'+action.result.errormsg);
                        Ext.getCmp('CreateFormID').close();
                    }
       					/*
       					root.expand(null, null, function(){
                        	var values = Ext.util.JSON.decode(response.responseText);
                            var name = values[0].name;
                            var mid = values[0].id;
                        	var newNodeCfg = {                                
                                text : mname,
                                id   : ,
                                leaf : true
                            }
                            var newNode = root.insert(newNodeCfg, root.firstChild);                                                                                                                                              
                        }, this);
                        //mname.setValue('');*/
	            });
	        }
	  }]
	});

	var createWindow = new Ext.Window({
		id: 'CreateFormID',
		frame:false,
		title:'Add new',
		width:330,
		closable: true,
		items: addForm
	}); 
	createWindow.show();
};


var createEditForm = function(mname)
{
	var type_item = getTreeItemID();
	var EditForm = new Ext.FormPanel({
	  url: 'application/update?'+type_item,
	  method: 'GET',
	  autoDestroy: true,
	  buttonAlign: 'center',
	  monitorValid:true,
	  items: [{
	          xtype: 'textfield',
	          id: 'name',
	          text: mname,
	          value: mname,
	          fieldLabel: 'name',
	          allowBlank:false,
	          anchor: '90%'
	  }],
	  buttons: [{
	        text: 'Update',
	        formBind:true,
	        handler: function() {
	            EditForm.getForm().submit({
	                waitTitle: 'please wait...',
	                waitMsg: 'wait...',
   	                success: function(form, action) {
       					Ext.Msg.alert('Status', 'Action is successfully.');
                        Ext.getCmp('TreeID').getRootNode().reload();
                        Ext.getCmp('EditFormID').close();
    				},
    				failure: function(form,action){
                        Ext.Msg.alert('Status', 'Action is failed:'+action.result.errormsg);
                        Ext.getCmp('EditFormID').close();
                    }    				
	            });
	        }
	  }]
	});

	var createWindow = new Ext.Window({
		id: 'EditFormID',
		frame:false,
		title:'Edit',
		width:330,
		closable: true,
		items: EditForm
	}); 
	createWindow.show();
};

var addItem = function(ev){
	createAddForm();
}

/*
var editDeveloperCallback = function(mid,name){
	createEditForm(mid,name);
}*/

var editItem = function(ev){
	//console.info("This is editDeveloper");
	var node = Ext.getCmp('TreeID').getSelectionModel().getSelectedNode();
	//var id = node.id;
	var isroot = node.isRoot;
	var devname = node.attributes.text;
	if (!isroot){
		createEditForm(devname);
		/*
		Ext.Ajax.request({
	       	url: 'developer/getnamebyid',
	        method: 'GET',
	   	    success: function(response, opts){
	    		var values = Ext.util.JSON.decode(response.responseText);
	    		var name = values[0].name;
	    		var mid = values[0].id;
	    		this.editDeveloperCallback(mid, name);
	    	},
		    params: {node: node.id}
		});*/
	}
}

var deleteItem = function(ev){
	//console.info("This is deleteDeveloper");
	var type_item = getTreeItemID();
	var node = Ext.getCmp('TreeID').getSelectionModel().getSelectedNode();
	var id = node.id;
	var isroot = node.isRoot;
	var devname = node.attributes.text
	if (!isroot){
   		Ext.Msg.show({
			title:'Delete',
			msg: 'item ['+devname+'] will be deleted. Are you sure?',
			buttons: Ext.Msg.YESNO,
			fn: function(buttonId,text){
				if (buttonId == 'yes')
					sendDeleteDevAjaxRequest(id,devname);
				//else
				//	console.info('CLICKtoNO')
				},
			animEl: 'elId',
			icon: Ext.MessageBox.QUESTION
		});		        
		var sendDeleteDevAjaxRequest = function(id,devname){		
			Ext.Ajax.request({
		       	url: 'application/delete?'+type_item,
		        method: 'GET',
		   	    success: function(response, opts){
		   	    	Ext.Msg.alert('Status', 'Item has been deleted successfully.');
		   	    	root = Ext.getCmp('TreeID').getRootNode();
		   	    	//root.remove(id);
		   	    	//root.expand();
                    root.reload();		   	    	
			    },
			    params: {node: node.id}
			});
		}
	}
}

var contextMenuActions = function(node, evtObj)
{
	//root  =  node.getOwnerTree().getRootNode()
	node.select();
	var ctxMenu = node.getOwnerTree().contextMenu;	
	if(!ctxMenu){
		Ext.MessageBox.alert("ctxMenu error");
	}
	ctxMenu.contextNode = node;
	var addItem = ctxMenu.getComponent('add');
	var editItem = ctxMenu.getComponent('edit');
	var deleteItem = ctxMenu.getComponent('delete');	
	addItem.disable();
	deleteItem.disable();
	editItem.disable();
	// VISIBILITY
	if (node.isRoot)
		addItem.enable();		
	else{
		addItem.enable();
		editItem.enable();
		deleteItem.enable();		
	}
	//ACTIONS
	if (node.isRoot){
		var action = 1;
	}
	ctxMenu.showAt(evtObj.getXY());
	evtObj.stopEvent();
};

var Tree = Ext.extend(Ext.tree.TreePanel, {
	id: 'TreeID',
	autoscroll:  true,
    autoload: true,
    loader: new Ext.tree.TreeLoader({
		url: 'application/getTree',
		requestMethod: 'GET'}),
	root:{
        nodeType: 'async',
        text: 'mera',		            
        orgid: '1'
    },
    contextMenu: new Ext.menu.Menu({
    	items: [{itemId: 'add', text:'Add', handler: addItem},
    			{itemId: 'edit', text: 'Edit', handler: editItem},
    			{itemId: 'delete', text:'Delete', handler: deleteItem}],
    	id: "contextMenuID"
    }),
    listeners:{
    	contextmenu: contextMenuActions,
		click: function(node, e){
       		renderTo: Ext.getBody();
       		handler: getGridItems(node.id);
	   	}
    },
	initComponent: function(){				
				Tree.superclass.initComponent.call(this);
	}    
});


Ext.reg('TreeID', Tree);